import { messages } from "share/common";
import React, { Component } from "react";
import { Form, Input, Row, Col, Checkbox, Card, Badge, Select, Icon, Radio, Table } from "antd";
import AdvanceTable from "components/advanced-table";
import HotelConfigUtil from "../hotel-config-util";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;

@Form.create()
class HotelCardForm extends Component {
  constructor(props) {
    super(props);
    this.iconStyle = {
      marginTop: 36,
      fontSize: 22,
      marginLeft: 6,
      color: "#1890ff",
    };
    this.state = {
      value: {}, // 初始值
      phone: [], // 客服电话
    };
  }

  componentWillMount() {
    const { value } = this.props;
    const phone = value.servicePhone ? value.servicePhone.split(",") : [""];
    this.setState({ value: value, phone: phone });
  }

  onInputFormChange = () => {
    setTimeout(() => {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          const { value } = this.state;
          const accountTemplate = JSON.parse(value.accountTemplate);
          const numbers = [];
          for (let key in values) {
            // 筛选出客服电话
            if (key.includes("serverPhone")) {
              if (values[key]) {
                numbers.push(values[key]);
              }
            }
          }
          for (let key in accountTemplate) {
            // 筛选出基础字段
            accountTemplate[key] = values[key] || "";
          }
          value.servicePhone = numbers.join(",");
          value.signEnabled = values.signEnabled;
          value.account = JSON.stringify(accountTemplate);
          this.setState({ value });
          this.onChange(value);
        }
      });
    });
  };

  onChange = (result) => {
    const { onChange } = this.props;
    onChange && onChange(result);
  };

  commonTitle = (isOpen, title) => {
    return (
      <div>
        <h3 style={{ display: "inline" }}>{title}</h3>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        {isOpen ? (
          <Badge status="success" text={messages("supplier-1.key351") /*已启用*/} />
        ) : (
          <Badge status="default" text={messages("supplier-1.key124") /*未启用*/} />
        )}
      </div>
    );
  };

  onAddPhoneNumber = (index) => {
    const { phone } = this.state;
    if (index === 0) {
      phone.push("");
    } else {
      phone.splice(index, 1);
    }
    this.setState({ phone });
  };

  parseAccount = (data) => {
    const account = data.account ? JSON.parse(data.account) : {};
    const accountTemplate = JSON.parse(data.accountTemplate);
    const arr = [];
    for (let keyName in accountTemplate) {
      if (keyName === "payType") {
        arr.push({
          labelName: "*" + messages("supplier-1.key443") /*以下配置项需与华住在商务上提前确认*/,
          value: "other",
        });
      }
      arr.push({
        labelName: keyName,
        value: account[keyName] || "",
      });
    }
    return arr;
  };

  render() {
    let spanNum2 = 12;
    const { getFieldDecorator } = this.props.form;
    const { value, phone } = this.state;
    const account = this.parseAccount(value);
    let formLayout = { width: "90%", display: "inline-block" };
    return (
      <div>
        <Card type="inner" title={this.commonTitle(value.vendorEnabled, value.vendorName)}>
          <Row>
            <Col span={5}>
              <FormItem label={messages("supplier-1.key352") /*是否启用*/}>
                {getFieldDecorator("signEnabled", {
                  initialValue: value.signEnabled || false,
                  valuePropName: "checked",
                })(<Checkbox onChange={this.onInputFormChange}>{messages("supplier-1.key35") /*启用temp*/}</Checkbox>)}
              </FormItem>
            </Col>
            <Col span={19}>
              <Row style={{ paddingBottom: 30 }}>
                {account.map((item, index) => {
                  spanNum2 = this.parseFormComponentSpan(item.labelName);
                  if (item.value === "other") {
                    return (
                      <Col span={24} style={{ marginTop: index > 1 ? 40 : 0 }}>
                        {item.labelName}
                      </Col>
                    );
                  }
                  return (
                    <Col
                      span={spanNum2}
                      style={{
                        marginTop: index > 1 && item.labelName !== "payType" ? 40 : 0,
                      }}
                    >
                      <FormItem label={this.parseFormLabelName(item.labelName)} style={formLayout}>
                        {getFieldDecorator(item.labelName, {
                          initialValue: item.value || this.parseFormComponentValue(item.labelName),
                        })(this.parseFormComponent(item.labelName))}
                      </FormItem>
                    </Col>
                  );
                })}
              </Row>
            </Col>
          </Row>
          <br />
          <Row>
            <Col span={5}>
              <FormItem label={messages("supplier-1.key353") /*客服电话*/} />
            </Col>
            <Col span={19}>
              <Row style={{ paddingBottom: 30 }}>
                {phone.map((item, index) => {
                  return (
                    <Col span={spanNum2} style={{ marginTop: index > 1 ? 12 : 0 }}>
                      <FormItem label={messages("supplier-1.key353") /*客服电话*/ + index + 1} style={formLayout}>
                        {getFieldDecorator(`serverPhone${index}`, {
                          initialValue: item || "",
                        })(<Input onChange={this.onInputFormChange} />)}
                      </FormItem>
                      <Icon
                        onClick={() => this.onAddPhoneNumber(index)}
                        type={index != 0 ? "minus-circle" : "plus-circle"}
                        style={this.iconStyle}
                      />
                    </Col>
                  );
                })}
              </Row>
            </Col>
          </Row>
          {value.vendorCode === "VENDOR:HOTELPLATFORM:HUAZHU" && (
            <div>
              <ul style={{ paddingLeft: 18 }}>
                <li>{messages("supplier-1.key444") /*海友酒店全线无早餐*/}</li>
                <li>{messages("supplier-1.key445") /*早餐实际为床位早，最多不超过2份*/}</li>
                <li>{messages("supplier-1.key446") /*以下三家桔子酒店无早餐*/}</li>
              </ul>
              <Table {...this.simpleTableOption()} />
            </div>
          )}
        </Card>
      </div>
    );
  }

  simpleTableOption = () => {
    const option = {
      rowKey: (record, index) => record.id || index,
      columns: HotelConfigUtil.huazhuHotel("column"),
      pagination: false,
      dataSource: HotelConfigUtil.huazhuHotel("data"),
      bordered: true,
    };
    return option;
  };

  /**
   * 字段属性别称
   * @param name 字段
   * @return {*}
   */
  parseFormLabelName = (name) => {
    const names = {
      payType: messages("supplier-1.key447") /*付款方式*/,
      agentId: messages("supplier-1.key448") /*卡号*/,
      authCode: messages("supplier-1.key449") /*验证码*/,
      guaranteeType: messages("supplier-1.key450") /*月结模式下担保方式配置*/,
      isViewTaxPrice: messages("supplier-1.key451") /*月结模式下前端是否显示含税价*/,
      isBreakfast: messages("supplier-1.key452") /*是否含早*/,
      guaranteeCancelLastTime: messages("supplier-1.key453") /*担保订单取消政策系显示配置*/,
    };
    if (names[name]) {
      return names[name];
    }
    return name;
  };
  /**
   * 根据字段返回对应的表单组件
   * @param name
   */
  parseFormComponent = (name) => {
    switch (name) {
      case "payType":
        return (
          <RadioGroup disabled onChange={this.onInputFormChange}>
            <Radio value="1">{messages("supplier-1.key454") /*支付宝代扣*/}</Radio>
            <Radio value="2">{messages("supplier-1.key455") /*到店付款*/}</Radio>
            <Radio value="3">{messages("supplier-1.key456") /*预付（个人支付）*/}</Radio>
            <Radio value="4">{messages("supplier-1.key457") /*月结*/}</Radio>
          </RadioGroup>
        );
      case "guaranteeType":
        return (
          <RadioGroup onChange={this.onInputFormChange}>
            <Radio value="1">{messages("supplier-1.key458") /*需担保*/}</Radio>
            <Radio value="0">{messages("supplier-1.key459") /*无需担保*/}</Radio>
          </RadioGroup>
        );
      case "isViewTaxPrice":
        return (
          <RadioGroup disabled onChange={this.onInputFormChange}>
            <Radio value="1">{messages("supplier-1.key460") /*显示*/}</Radio>
            <Radio value="0">{messages("supplier-1.key461") /*不显示*/}</Radio>
          </RadioGroup>
        );
      case "isBreakfast":
        return (
          <RadioGroup onChange={this.onInputFormChange}>
            <Radio value="1">{messages("supplier-1.key462") /*含早*/}</Radio>
            <Radio value="0">{messages("supplier-1.key463") /*不含早*/}</Radio>
          </RadioGroup>
        );
      case "guaranteeCancelLastTime":
        return (
          <Select onChange={this.onInputFormChange}>
            <Option value="18:00">{messages("supplier-1.key464") /*入住当天18:00前可取消*/}</Option>
            <Option value="20:00">{messages("supplier-1.key465") /*入住当天20:00前可取消*/}</Option>
          </Select>
        );
      default:
        return <Input onChange={this.onInputFormChange} />;
    }
  };
  /***
   * 根据字段查找对应的可选值或者初始值包装
   * @param name
   */
  parseFormComponentValue = (name) => {
    const names = {
      payType: "4",
      isViewTaxPrice: "0",
    };
    if (names[name]) {
      return names[name];
    }
    return "";
  };
  /***
   * 根据字段查设置宽度比例
   * @param name
   */
  parseFormComponentSpan = (name) => {
    const names = {
      payType: 24,
    };
    if (names[name]) {
      return names[name];
    }
    return 12;
  };
}

export default HotelCardForm;
